package research.mail;

import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * 
 * 很早之前写的一个发送邮件的例子。
 * 
 * 如果报协议错可能还需要加入对应的协议jar
 *
 */
public class SendMail {
	
	public static void send(SendInfo sendInfo) {
		
		//服务器设置
		Properties props = new Properties();
		props.put("mail.smtp.host", sendInfo.getMailHost());   //邮件服务器地址
		props.put("mail.from", sendInfo.getMailFrom());        //发送人
		props.put("mail.smtps.port", SendInfo.SMTP_PORT);      //SMTP端口：25
		props.put("mail.smtp.auth", "true");                   //用户验证
		
		MyAuthenticator myAuthenticator = new MyAuthenticator(sendInfo.getMailFrom(), sendInfo.getMailFromPwd());
		
		Session session = Session.getInstance(props, myAuthenticator);
		
		MimeMessage msg = new MimeMessage(session);
		
		try {
			Address[] tos = null;
			Address[] ccs = null;
			String[] receiverForTO = sendInfo.getMailTo();
			String[] receiverForCC = sendInfo.getMailCC();
			//发送人
			if (receiverForTO != null) {
				tos = new InternetAddress[receiverForTO.length];
				for (int i = 0; i < receiverForTO.length; i++) {
					tos[i] = new InternetAddress(receiverForTO[i]);
				}
			}
			//抄送人
			if (receiverForCC != null) {
				ccs = new InternetAddress[receiverForCC.length];
				for (int i = 0; i < receiverForCC.length; i++) {
					ccs[i] = new InternetAddress(receiverForCC[i]);
				}
			}
			
			msg.setFrom();
			msg.setRecipients(Message.RecipientType.TO, tos);
			msg.setRecipients(Message.RecipientType.CC, ccs);
			msg.setSubject(sendInfo.getSubject());
			msg.setText(sendInfo.getText());
			msg.setSentDate(new Date());
			
			Transport.send(msg);
			
		} catch (MessagingException mex) {
			System.out.println("send failed, exception: " + mex);
		}
	}
}
